package me.youline.dataServer.script;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

public class SQLScriptSplitApplication {

	private List<StringBuilder> fileBuilderList = new ArrayList<StringBuilder>();
	
	private List<FileRecorder> fileRecorders = new ArrayList<FileRecorder>();
	
	private int createFileCount = 0;
	
	
	public static void main(String[] args) throws IOException {
		SQLScriptSplitApplication application = new SQLScriptSplitApplication();
		application.createSplitScriptFile();
	}
	
	
	public void createSplitScriptFile() throws IOException{
		ContentStrProcessor processor = new ContentStrProcessor();
		processor.buildRootDir();
		ClassPathResource resource = new ClassPathResource("youline-database.sql");
		List<String> list = IOUtils.readLines(resource.getInputStream());
		
		for(String s : list){
			if(this.isStartFlag(s)){
				newFileBuilder();
				continue;
			}else if(this.isEndFlag(s)){
				endCurrentBuilder();
				continue;
			}
			if(StringUtils.isBlank(s)){
				continue;
			}
			if(processor.isTableNamePosition(s)){
				fileRecorders.add(new FileRecorder(this.getCurrentBuilder(),processor.decideTableName(s)));
			}
			processor.doProcess(s);
		}
		processor.doBuildFiles();
	}
	
	static class FileRecorder{
		
		private final StringBuilder content;
		
		private final String tableName;

		public FileRecorder(StringBuilder content, String tableName) {
			this.content = content;
			this.tableName = tableName;
		}

		public StringBuilder getContent() {
			return content;
		}

		public String getTableName() {
			return tableName;
		}
		
	}
	
	 class ContentStrProcessor{
		 
		 private static final String SCRIPT_DIR = "d://sqlScripts";
		 
		 private static final String NAME_FORMAT = "youline-test[%s].sql";
		 
		 private static final String TABLE_NAME_FLAG = "CREATE TABLE IF NOT EXISTS";
		 
		 
		 public void buildRootDir() throws IOException{
				File dir = new File(SCRIPT_DIR);
				dir.delete();
				if(!dir.exists()){
					dir.mkdirs();
				}
				
		 }
		 
		public void doProcess(String str){
			getCurrentBuilder().append(str);
		}
		
		public boolean isTableNamePosition(String str){
			return str.contains(TABLE_NAME_FLAG);
			
		}
		
		public String decideTableName(String str){
			Pattern p =Pattern.compile(TABLE_NAME_FLAG+" `(\\w+)`.+");
			Matcher m = p.matcher(str);
			if(m.matches()){
				return m.group(1).trim();
			}
			throw new RuntimeException("can't decide table name");
		}
		
		public void doBuildFiles() throws IOException{
			for(FileRecorder r : fileRecorders){
				File outputFile = new File(this.decideFileUrl(r.getTableName()));
				outputFile.createNewFile();
				IOUtils.write(r.getContent().toString(), new FileOutputStream(outputFile));
			}
		}
		
		private String decideFileUrl(String tableName){
			return SCRIPT_DIR+"/"+String.format(NAME_FORMAT, tableName);
		}
	}
	 
	public StringBuilder newFileBuilder(){
		StringBuilder builder = new StringBuilder();
		fileBuilderList.add(builder);
		return builder;
	}
	
	public StringBuilder getCurrentBuilder(){
		if(fileBuilderList.size() <= createFileCount){
			throw new RuntimeException("file builder has been ended ,you can't re-get");
		}
		return fileBuilderList.get(createFileCount);
	}
	
	public void endCurrentBuilder(){
		createFileCount++;
	}
	
	public boolean isStartFlag(String s){
		return s.startsWith("--start");
	}
	
	public boolean isEndFlag(String s){
		return s.startsWith("--end");
	}
}
